package com.example.friend.manger;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;

import com.example.core.constants.CacheConstants;
import com.example.core.constants.Constants;
import com.example.core.domain.TableDataInfo;
import com.example.friend.domain.Message;
import com.example.friend.domain.MessageText;
import com.example.friend.domain.vo.MessageCacheVO;
import com.example.friend.domain.vo.MessageTextCacheVO;
import com.example.friend.domain.vo.UserMessageVO;
import com.example.friend.mapper.MessageMapper;
import com.example.friend.mapper.MessageTextMapper;
import com.example.redis.service.RedisService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.function.Function;
import java.util.stream.Collectors;

@Component
public class MessageCacheManager {

    @Autowired
    private MessageMapper messageMapper;

    @Autowired
    private MessageTextMapper messageTextMapper;

    @Autowired
    private RedisService redisService;

    public TableDataInfo selectUserMessageList(Long userId, int start, int end) {
        String key = getUserMsgListKey(userId);
        List<UserMessageVO> userMessageVOList =
                redisService.getCacheListByRange(key, start, end - 1, UserMessageVO.class);
        int total = 0;
        TableDataInfo info = TableDataInfo.empty();
        if (CollectionUtils.isEmpty(userMessageVOList)) {
            userMessageVOList = refreshMessageList(userId);
            if (CollectionUtils.isEmpty(userMessageVOList)) {
                return info;
            }
            total = userMessageVOList.size();
            if (start >= total) {
                return info;
            }
            if (end >= total) {
                end = total;
            }
            userMessageVOList = userMessageVOList.subList(start, end);
        } else {
            total = redisService.getListSize(key).intValue();
            assembleUserMessageVOList(userMessageVOList);
        }
        info.setTotal((long) total);
        info.setRows(userMessageVOList);
        return info;
    }

    public UserMessageVO detail(Long messageId, Long textId) {
        String readStatusKey = getMsgReadStatusKey();
        Integer readStatus = redisService.getCacheMapValue(readStatusKey, String.valueOf(messageId), Integer.class);
        if (readStatus == null || !readStatus.equals(Constants.TRUE)) {
            //设置用户消息状态为已读
            redisService.setCacheMapValue(readStatusKey, String.valueOf(messageId), Constants.TRUE);
            messageMapper.update(new UpdateWrapper<Message>()
                    .set("status", Constants.TRUE)
                    .eq("message_Id", messageId));
        }
        UserMessageVO detail = redisService
                .getCacheMapValue(getMsgDetailKey(), String.valueOf(textId), UserMessageVO.class);
        if (detail == null) {
            MessageText messageText = messageTextMapper.selectOne(new LambdaQueryWrapper<MessageText>()
                    .select(MessageText::getTextId,
                            MessageText::getMessageType,
                            MessageText::getMessageTitle,
                            MessageText::getMessageContent)
                    .eq(MessageText::getTextId, textId));
            if (messageText == null) {
                return null;
            }
            detail = new UserMessageVO();
            BeanUtils.copyProperties(messageText, detail);
            redisService.setCacheMapValue(getMsgDetailKey(), String.valueOf(textId), messageText);
        }
//        detail.setStatus(Constants.TRUE);
        return detail;
    }

    public void delete(Long userId, Long messageId) {
        String key = getUserMsgListKey(userId);
        List<MessageCacheVO> userMessageVOList =
                redisService.getCacheListByRange(key, 0, -1, MessageCacheVO.class);
        if (CollectionUtils.isEmpty(userMessageVOList)) {
            return;
        }
        for (int index = 0; index < userMessageVOList.size(); index++) {
            MessageCacheVO messageCacheVO = userMessageVOList.get(index);
            if (messageCacheVO.getMessageId().equals(messageId)) {
                redisService.removeForList(key, index);
            }
        }
    }

    private void assembleUserMessageVOList(List<UserMessageVO> userMessageVOList) {
        Map<Long, MessageTextCacheVO> textCacheVOMap = getMsgTextMap(userMessageVOList);
        for (UserMessageVO userMessageVO : userMessageVOList) {
            MessageTextCacheVO textCacheVO = textCacheVOMap.get(userMessageVO.getTextId());
            if (textCacheVO == null) {
                MessageText messageText = messageTextMapper.selectById(userMessageVO.getTextId());
                if (messageText != null) {
                    textCacheVO = new MessageTextCacheVO();
                    BeanUtils.copyProperties(messageText, textCacheVO);
                    redisService.setCacheMapValue(
                            getMsgDetailKey(), String.valueOf(userMessageVO.getTextId()), textCacheVO);
                }
            }
            if (textCacheVO != null) {
                userMessageVO.setMessageTitle(textCacheVO.getMessageTitle());
                userMessageVO.setMessageContent(textCacheVO.getMessageContent());
                userMessageVO.setMessageType(textCacheVO.getMessageType());
            }
//            if (userMessageVO.getStatus() == null || userMessageVO.getStatus().equals(Constants.FALSE)) {
//                Integer readStatus = getMessageReadStatus(userMessageVO.getMessageId());
//                userMessageVO.setStatus(readStatus);
//            }
        }
    }

//    private Integer getMessageReadStatus(Long messageId) {
//        String readStatusKey = getMsgReadStatusKey();
//        Integer readStatus = redisService.getCacheMapValue(readStatusKey, String.valueOf(messageId), Integer.class);
//        if (readStatus == null) {
//            Message message = messageMapper.selectById(messageId);
//            return message.getStatus();
//        }
//        return readStatus;
//    }

    private Map<Long, MessageTextCacheVO> getMsgTextMap(List<UserMessageVO> userMessageVOList) {
        List<Long> textIdSet = userMessageVOList.stream().map(UserMessageVO::getTextId).collect(Collectors.toList());
        String msgDetailKey = getMsgDetailKey();
        List<MessageTextCacheVO> textCacheVOList =
                redisService.getMultiCacheMapValue(msgDetailKey, textIdSet, MessageTextCacheVO.class);
        if (CollectionUtils.isEmpty(textCacheVOList)) {
            //刷新详情缓存
            textCacheVOList = messageTextMapper.selectMsgDetailCacheList(textIdSet);
            Map<Long, MessageTextCacheVO> textCacheVOMap = textCacheVOList.stream()
                    .collect(Collectors.toMap(MessageTextCacheVO::getTextId, Function.identity()));
            //存储消息详情到缓存
            redisService.setCacheMap(msgDetailKey, textCacheVOMap);
            return textCacheVOMap;
        }
        return textCacheVOList.stream().collect(Collectors.toMap(MessageTextCacheVO::getTextId, Function.identity()));
    }

    private List<UserMessageVO> refreshMessageList(Long userId) {
        //联表查询当前用户的收到的消息
        List<UserMessageVO> userMessageVOList = messageMapper.selectUserMessageList(userId);
        if (CollectionUtils.isEmpty(userMessageVOList)) {
            return null;
        }
        List<MessageCacheVO> messageCacheVOList = new ArrayList<>();
        Map<String, MessageTextCacheVO> textCacheVOMap = new HashMap<>();
        for (UserMessageVO userMessageVO : userMessageVOList) {
            MessageCacheVO messageCacheVO = new MessageCacheVO();
            BeanUtils.copyProperties(userMessageVO, messageCacheVO);
            messageCacheVOList.add(messageCacheVO);

            MessageTextCacheVO textCacheVO = new MessageTextCacheVO();
            BeanUtils.copyProperties(userMessageVO, textCacheVO);
            textCacheVOMap.put(String.valueOf(textCacheVO.getTextId()), textCacheVO);
        }
        //存储用户消息列表到缓存
        String userMsgListKey = getUserMsgListKey(userId);
        redisService.rightPushAll(userMsgListKey, messageCacheVOList);
        //存储消息详情到缓存
        String msgDetailKey = getMsgDetailKey();
        redisService.setCacheMap(msgDetailKey, textCacheVOMap);
        return userMessageVOList;
    }

    private String getMsgReadStatusKey() {
        return CacheConstants.USER_MESSAGE_READ_STATUS;
    }

    private String getUserMsgListKey(Long userId) {
        return CacheConstants.USER_MESSAGE_LIST + userId;
    }

    private String getMsgDetailKey() {
        return CacheConstants.MESSAGE_DETAIL;
    }
}
